﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ueEngine.Framework.Common;
using ueEngine.Biz.Inf.Entities.DBSupport;
using ueEngine.Biz.Core.ExServer.WorkPool.WorkHandle.FullSearch;
using ueEngine.Biz.Inf.LogicEntity;
using ueEngine.Biz.Core.ExServer.WorkPool;
using ueEngine.Biz.Inf.Entities;

namespace ueEngine.Biz.Core.AppService.Support
{
    public class ExchangeBiz
    {
        //static int period = 30 * 60 * 1000;
        //static object sync_key = new object();
        //static System.Threading.Timer timer = null;
        //static BizTask()
        //{
        //    timer = new System.Threading.Timer(
        //        o =>
        //        {
        //            DoIndex();
        //        }, null, 0, period);
        //}
        public static void DoIndex()
        {
            LogHelper.Write(CommonLogger.ExServer, LogLevel.Trace, "定时任务开始执行");
            using (Context ctx = new Context())
            {
                //查询300个，招募单通过了审核，且未创建索引的职位信息
                var data = (from p in ctx.Position
                            join r in ctx.RecruitSheet
                                 on p.RecruitId equals r.Id
                            join c in ctx.DepositCompany
                                on r.DepositCompanyId equals c.Id
                            join cop in ctx.Corporation
                                on r.Recruiter equals cop.Agent
                            where r.IsVerify && !p.IsIndex
                            orderby p.Id ascending
                            select new
                            {
                                Position = new
                                {
                                    PositionId = p.Id,
                                    RecruitId = p.RecruitId,
                                    PositionDescript = p.PositionDescript,
                                    PositionName = p.PositionName,
                                    PositionType = p.PositionType,
                                    PositionLevel = p.PositionLevel,
                                    PositionPriority = p.PositionPriority
                                },
                                RecruitSheet = new
                                {
                                    Recruiter = r.Recruiter,
                                    Title = r.Caption,
                                    RecruitId = r.Id,
                                    //Description = r.Description,
                                    WorkArea = r.WorkArea,
                                    WorkAddress = r.WorkAddress,
                                    RecruitType = r.RecruitType,
                                    RecruitSubject = r.RecruitSubject
                                },
                                c.CompanyName,
                                cop.CertificationLevel
                            })
                            .Take(900)
                            .ToList()
                            .Select(c => new PositionItem()
                            {
                                Recuriter = c.RecruitSheet.Recruiter,
                                Title = c.RecruitSheet.Title,
                                PositionId = c.Position.PositionId,
                                RecuritId = c.RecruitSheet.RecruitId,
                                //RecuritDescript = c.RecruitSheet.Description,
                                PositionName = c.Position.PositionName,
                                PositionType = (PositionType)c.Position.PositionType,
                                PublishDate = DateTime.Now,
                                WorkArea = (AreaCode)c.RecruitSheet.WorkArea,
                                WorkAddress = c.RecruitSheet.WorkAddress,
                                URL = "/home/jobdetail_" + c.RecruitSheet.RecruitId,
                                Priority = (int)c.Position.PositionPriority,
                                PositionLevel = (int)c.Position.PositionLevel,
                                PositionDescript = c.Position.PositionDescript,
                                RecruitSheetType = (RecruitSheetType)c.RecruitSheet.RecruitType,
                                RecruitSheetSubject = (RecruitSheetSubject)c.RecruitSheet.RecruitSubject,
                                CompanyName = c.CompanyName,
                                CertificationLevel = (Inf.LogicEntity.CertificationLevel)c.CertificationLevel
                            })
                            .ToList();
                if (!data.Any())
                {
                    return;
                }
                for (int i = 0, len = data.Count % 300 == 0 ? data.Count / 300 : data.Count / 300 + 1; i < len; i++)
                {
                    int startidx = i * 300;
                    int count = 300 > data.Count - i * 300 ? data.Count - i * 300 : 300;
                    var list = data.GetRange(startidx, count);
                    //加入池执行
                    WorkPool.Append<List<PositionItem>>(WorkType.index_position, list, () =>
                    {
                        //修改这些职位索引状态为已索引
                        int affect = ctx.Update<Position>()
                            .Set(c => c.IsIndex, true)
                            .WhereIn(c => c.Id, list.Select(c => c.PositionId).ToList())
                            .End()
                            .Excute();
                        LogHelper.Write(CommonLogger.ExServer, LogLevel.Trace, "执行修改职位索引状态为已索引，影响行数：" + affect);
                    });
                }

            }
        }

        public static void DoAutoRefresh()
        {
            try
            {
                LogHelper.Write(CommonLogger.System, LogLevel.Trace, "执行DoAutoRefresh");
                string deleteitems = string.Empty;
                string refreshitems = string.Empty;
                using (System.Data.SqlClient.SqlConnection con =
                    new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectStr"].ConnectionString))
                {
                    System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand(
                        "select * from RefreshRecord", con);
                    System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(com);
                    System.Data.DataSet ds = new System.Data.DataSet();
                    con.Open();
                    da.Fill(ds);
                    LogHelper.Write(CommonLogger.System, LogLevel.Trace, "执行DoAutoRefresh，查询到：" + ds.Tables[0].Rows.Count + "条数据");
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
                        {
                            int id = Int32.Parse(dr["id"].ToString());
                            int recruitId = Int32.Parse(dr["recruitId"].ToString());
                            DateTime enddate = DateTime.Parse(dr["enddate"].ToString());
                            if (enddate <= DateTime.Parse(DateTime.Now.ToString("yyyyMMdd")))
                            {
                                deleteitems += id.ToString() + ",";
                            }
                            refreshitems += id.ToString() + ",";

                        }
                    }
                    LogHelper.Write(CommonLogger.System, LogLevel.Trace, "执行DoAutoRefresh，查询到refreshitems:" + refreshitems + ",deleteitems:" + deleteitems);
                    if (!String.IsNullOrEmpty(refreshitems))
                    {
                        refreshitems = refreshitems.EndsWith(",") ? refreshitems.Remove(refreshitems.Length - 1) : refreshitems;
                        string sql = "update recruitsheet set refresh = '" + DateTime.Now.ToString() + "' where id in (" + refreshitems + ")";
                        com.CommandText = sql;
                        int affact = com.ExecuteNonQuery();
                        if (affact != refreshitems.Split(',').Length)
                        {
                            LogHelper.Write(CommonLogger.ExServer, LogLevel.Info, "执行刷新发布时间更新行数和提交行数不一致");
                        }
                    }
                    if (!String.IsNullOrEmpty(deleteitems))
                    {
                        deleteitems = deleteitems.EndsWith(",") ? deleteitems.Remove(deleteitems.Length - 1) : deleteitems;
                        string sql = "delete recruitsheet where id in (" + deleteitems + ")";
                        com.CommandText = sql;
                        int affact = com.ExecuteNonQuery();
                        if (affact != deleteitems.Split(',').Length)
                        {
                            LogHelper.Write(CommonLogger.ExServer, LogLevel.Info, "执行删除发布时间更新行数和提交行数不一致");
                        }
                    }

                    con.Close();
                }
            }
            catch (Exception e)
            {
                LogHelper.Write(CommonLogger.ExServer, LogLevel.Error, e);
            }
        }
    }
}
